package plus.lgx.textsearcher.util;

import java.text.ParseException;
import java.util.Locale;

import static plus.lgx.textsearcher.constant.Const.FILE_SIZE_SUFFIX;

/**
 * Class name: FileUtil
 *
 * Create time: 12/21/22 7:53 PM
 *
 * @author lgx
 * @version 1.0
 */
public class FileUtil {

    public static String toFileLength(long len) {
        int i = 0, k = 0;
        long j = len;
        while (j > 1023) {
            k = (int) (j % 1024 / 1024F * 100);
            j /= 1024;
            i++;
        }
        return j + (k > 0 ? k > 9 ? "." + k : ".0" + k : "") + FILE_SIZE_SUFFIX[i];
    }

    public static long fromFileLength(String fileLength) throws ParseException {
        try {
            return Long.parseLong(fileLength);
        } catch (NumberFormatException ignored) {}

        String suffix = fileLength.substring(fileLength.length() - 2).toUpperCase(Locale.ROOT);
        if (!suffix.endsWith("B")) {
            throw new ParseException("parse file size error. ", fileLength.length() - 1);
        }

        String prefix = fileLength.substring(0, fileLength.length() - 2);
        long size = Long.parseLong(prefix);
        if (size <= 0) return 0;
        for (String s : FILE_SIZE_SUFFIX) {
            if (s.equals(suffix)) {
                return size;
            }
            size <<= 10;
        }

        try {
            return Long.parseLong(fileLength.substring(0, fileLength.length() - 1));
        } catch (NumberFormatException ignored) {}
        throw new ParseException("parse file size error. ", fileLength.length() - 2);
    }

}
